#!/usr/bin/env perl
#
# Copyright (c) 2012-2013 Jeffrey M. Squyres.  All rights reserved.
#
# $COPYRIGHT$
# 
# Additional copyrights may follow
# 
# $HEADER$
#

package RubySlippers::Decision::sosume;

use strict;
use RubySlippers::Messages;
use RubySlippers::Globals;
use RubySlippers::Config;
use RubySlippers::Engine;

# Local state

my $_state = STATE_UNKNOWN;
my $_start_time = time();
my $_timeout = 15 * 60;

# Values filled in from the main configuration
my @_devices;


#
# Set a specific state.  This is only a function because it avoids a
# little code duplication.
#
sub _set_state {
    my $state = shift;

    # Only set the state if it is actually changing
    if ($state != $_state) {
        $_state = $state;
        RubySlippers::Engine::Act($state);
    }
}

#
# This function is invoked by the Decide engine when a Query module
# wants to report new information.  We use that new information to
# make a decision.
#
sub _sosumi_decide {
    my $args = shift;

    # We (currently) only look at the output from the sosumi query
    # module
    if (!defined($args->{query}) || $args->{query} ne "sosumi") {
        Debug("Info is not from sosumi; ignoring");
        return;
    }

    # Look at whatever the data is that came from the sosumi Query
    # module and decide whether you want to change the current state.
    # Remember that we start in the UNKNOWN state.  Then you call
    # _set_state() with STATE_HOME or STATE_NOT_HOME (which will call
    # the Act engine, which will call the Nest.pm Action plugin).

    # If we're still in the UNKNOWN state and it's been at least
    # timeout seconds since we started, then we should set NOT_HOME.
    if (STATE_UNKNOWN == $_state && time() > $_start_time + $_timeout) {
        _set_state(STATE_NOT_HOME);
    }
}

# Open the module.  We qualify to return a module if we find a list of
# home_devices or not_home_devices and an associated timeout.
#
sub open {
    # If we don't have a list of devices, then don't bother.
    @_devices = 
        RubySlippers::Config::parse_config_list("sosumi_devices", undef);
    if ($#_devices < 0) {
        Verbose("No sosumi_devices defined in config");
        Verbose("sosumi Decide plugin disqualifying itself");
        return undef;
    }

    # Return 1 module
    Verbose("sosumi returning Decision module");
    Verbose("    sosumi monitored devices: " . join(", ", @_devices) . "");
    my @ret;
    push(@ret, {
        decide => \&_sosumi_decide,
        name => "sosumi decide",
         });
    return \@ret;
}

1;
